package com.ludomancy.gamelib;

import com.ludomancy.gamelib.verlet.Edge;

public class MathHelper
{
	// 0 - distance
	// 1 - t
	// 2 - contactX
	// 3 - contactY
	public static float[] distanceFromPointToEdge(float px, float py, Edge edge, float[] out)
	{
		// find t for x
		float p0X = edge.v1.px;
		float p0Y = edge.v1.py;
		float p1X = edge.v2.px;
		float p1Y = edge.v2.py;
		
		float upper_part = (-( p1Y - p0Y ) * ( p0Y - py ) - ( p1X - p0X ) * ( p0X - px ));
		float denom = ( ( p1X - p0X ) * ( p1X - p0X ) + ( p1Y - p0Y ) * ( p1Y - p0Y ) );
		float t =  upper_part / denom;
		if( t < 0 ) 
		{
			t = 0;
		}
		else if( t > 1 )
		{
			t = 1;
		}
		float contactX = t * (p1X - p0X) + p0X;
		float contactY = t * (p1Y - p0Y) + p0Y;
		out[0] = dist(contactX, contactY, px, py);
		out[1] = t;
		out[2] = contactX;
		out[3] = contactY;
		return out;
	}
	
	public static float dist(float x0, float y0, float x1, float y1)
	{
		float a = x0 - x1;
		float b = y0 - y1;
		return (float)Math.sqrt(a*a + b*b);
	}
	
	public static float[] project(float v1x, float v1y, float v2x, float v2y, float[] out)
	{
		float dot = v1x * v2x + v1y * v2y;
		out[0] = dot * v2x;
		out[1] = dot * v2y;
		return out;
	}
	
	public static float[] normalize(float px, float py, float[] out)
	{
		float len = dist(0,0,px,py);
		out[0] = px/len;
		out[1] = py/len;
		return out;
	}


}
